package de.bk.timecalc.midlet.statemachine;

import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Form;

import de.bk.timecalc.midlet.Commands;

public class GuiStateOptions extends AbstractGuiState
{
  private static final int UP_INDEX = 0;
  private static final String UP_TEXT = "up";
  private static final int DOWN_INDEX = 1;
  private static final String DOWN_TEXT = "down";

  private Form form;
  private ChoiceGroup choiceGroup;

  GuiStateOptions(StateMachine stateMachine)
  {
    super(stateMachine);
  }

  void init()
  {
    this.createForm();
  }

  void enter()
  {
    this.resetForm();
    this.getDisplay().setCurrent(this.form);
  }

  void leave()
  {
    int selectedIndex = this.choiceGroup.getSelectedIndex();
    boolean timerCountsDown = selectedIndex == DOWN_INDEX;
    this.getStateMachine().getGame().setTimerCountsDown(timerCountsDown);
  }

  void destroy()
  {
    this.form = null;
  }

  private void createForm()
  {
    this.form = new Form("QL Time Calc Trainer - Options");
    CommandListener commandListener = new DefaultCommandListener(
        this);
    this.form.setCommandListener(commandListener);
    this.form.addCommand(Commands.exit);

    String[] values = new String[2];
    values[UP_INDEX] = UP_TEXT;
    values[DOWN_INDEX] = DOWN_TEXT;
    this.choiceGroup = new ChoiceGroup("Timer counts", ChoiceGroup.EXCLUSIVE,
        values, null);

    this.form.append(this.choiceGroup);
  }

  private void resetForm()
  {
    boolean timerCountsDown = this.getStateMachine().getGame()
        .isTimerCountsDown();
    if (timerCountsDown)
    {
      this.choiceGroup.setSelectedIndex(DOWN_INDEX, true);
    }
    else
    {
      this.choiceGroup.setSelectedIndex(UP_INDEX, true);
    }
  }
}
